// router/articleModel.js
const Router = require("koa-router");
const { MerchantManager } = require("../../mongodb/manager");
const { verifyToken } = require("../../middleware");

const router = new Router();

/**
 * @swagger
 * tags:
 *   name: Merchant
 *   description: 商家接口
 */

// 添加商家接口
/**
 * @swagger
 * /merchants:
 *   post:
 *     summary: 添加商家
 *     tags: [Merchant]
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               merchantname:
 *                 type: string
 *                 description: 商家名称
 *                 example: "阳光餐厅"
 *               erweimapic:
 *                 type: string
 *                 description: 商家二维码
 *                 example: "http://example.com/qrcode.png"
 *               info:
 *                 type: string
 *                 description: 商家简介
 *                 example: "提供各种美味的中餐"
 *               pictureurl:
 *                 type: string
 *                 description: 商家介绍图
 *                 example: "http://example.com/image.png"
 *               sort:
 *                 type: string
 *                 description: 商家分类
 *                 example: "美食"
 *               town:
 *                 type: string
 *                 description: 商家所属小镇
 *                 example: "阳光小镇"
 *     responses:
 *       200:
 *         description: 创建成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 merchantname:
 *                   type: string
 *                   example: "阳光餐厅"
 *                 erweimapic:
 *                   type: string
 *                   example: "http://example.com/qrcode.png"
 *                 info:
 *                   type: string
 *                   example: "提供各种美味的中餐"
 *                 pictureurl:
 *                   type: string
 *                   example: "http://example.com/image.png"
 *                 sort:
 *                   type: string
 *                   example: "美食"
 *                 town:
 *                   type: string
 *                   example: "市中心"
 *       400:
 *         description: 请求参数不合法
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 *                   example: "参数不合法"
 */
router.post("/", verifyToken("merchant"), async (ctx) => {
  try {
    const merchant = await MerchantManager.createMerchant(ctx.request.body);
    ctx.status = 200;
    ctx.body = merchant;
  } catch (error) {
    ctx.status = 400;
    ctx.body = { message: error.message };
  }
});

// 修改商家接口 TODO: 可能需要修改为商家权限
/**
 * @swagger
 * /merchants:
 *   put:
 *     summary: 修改商家信息
 *     tags: [Merchant]
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               merchantname:
 *                 type: string
 *                 description: 商家名称
 *                 example: "阳光餐厅"
 *               updateData:
 *                 type: object
 *                 description: 要更新的商家信息
 *                 properties:
 *                   erweimapic:
 *                     type: string
 *                     description: 商家二维码
 *                     example: "http://example.com/qrcode.png"
 *                   info:
 *                     type: string
 *                     description: 商家简介
 *                     example: "提供各种美味的中餐"
 *                   pictureurl:
 *                     type: string
 *                     description: 商家介绍图
 *                     example: "http://example.com/image.png"
 *                   sort:
 *                     type: string
 *                     description: 商家分类
 *                     example: "美食"
 *                   town:
 *                     type: string
 *                     description: 商家所属小镇
 *                     example: "月光小镇"
 *     responses:
 *       200:
 *         description: 修改成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 *                   example: "修改成功"
 *                 updatedMerchant:
 *                   type: object
 *                   description: 修改后的商家信息
 *                   properties:
 *                     merchantname:
 *                       type: string
 *                       example: "阳光餐厅"
 *                     erweimapic:
 *                       type: string
 *                       example: "http://example.com/qrcode.png"
 *                     info:
 *                       type: string
 *                       example: "提供各种美味的中餐"
 *                     pictureurl:
 *                       type: string
 *                       example: "http://example.com/image.png"
 *                     sort:
 *                       type: string
 *                       example: "美食"
 *                     town:
 *                       type: string
 *                       example: "阳光小镇"
 *       400:
 *         description: 请求参数不合法
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 *                   example: "merchantname is required."
 *       404:
 *         description: 找不到商家
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 *                   example: "Merchant not found"
 *       500:
 *         description: 服务器错误
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 *                   example: "更新商家信息时发生错误"
 */
router.put("/", verifyToken("admin"), async (ctx) => {
  const { merchantname, updateData } = ctx.request.body; // 获取请求参数

  let merchant;

  // 查找商家
  if (!merchantname) {
    ctx.status = 400;
    ctx.body = { message: "merchantname is required." };
    return;
  }

  merchant = await MerchantManager.getMerchantByMerchantname(merchantname);

  if (!merchant) {
    ctx.status = 404;
    ctx.body = { message: "Merchant not found" };
    return;
  }

  // 更新商家信息
  try {
    const updatedMerchant = await MerchantManager.updateMerchant(
      merchant._id,
      updateData,
    );
    ctx.status = 200;
    ctx.body = { message: "修改成功", updatedMerchant };
  } catch (error) {
    ctx.status = 400;
    ctx.body = { message: error.message };
  }
});

// 删除商家接口
/**
 * @swagger
 * /merchants:
 *   delete:
 *     summary: 根据商家名称删除商家
 *     tags: [Merchant]
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               merchantname:
 *                 type: string
 *                 description: 商家名称
 *                 example: "阳光餐厅"
 *     responses:
 *       200:
 *         description: 商家成功标记为已删除
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 *                   example: "Merchant successfully marked as deleted."
 *       400:
 *         description: 请求参数不合法
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 *                   example: "merchantname is required."
 *       404:
 *         description: 找不到商家
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 *                   example: "Merchant not found"
 *       500:
 *         description: 服务器错误
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 *                   example: "Failed to mark user as deleted."
 */
router.delete("/", verifyToken("admin"), async (ctx) => {
  const { merchantname } = ctx.request.body; // 查询字段

  // 检查请求体，确保至少有一个参数
  if (!merchantname) {
    ctx.status = 400;
    ctx.body = { message: "merchantname is required." };
    return;
  }

  let merchant;

  // 根据名称查找
  merchant = await MerchantManager.getMerchantByMerchantname(merchantname);

  // 如果不存在，返回错误
  if (!merchant) {
    ctx.status = 404;
    ctx.body = { message: "Merchant not found" };
    return;
  }

  // 使用已存在的标记删除方法
  try {
    await MerchantManager.deleteMerchantById(merchant._id);
    ctx.status = 200;
    ctx.body = { message: "Merchant successfully marked as deleted." };
  } catch (error) {
    ctx.status = 500; // 处理可能的服务器错误
    ctx.body = { message: "Failed to mark user as deleted." };
  }
});

// 获取所有商家名字列表接口
/**
 * @swagger
 * /merchants/list:
 *   get:
 *     summary: 获取所有商家列表
 *     tags: [Merchant]
 *     responses:
 *       200:
 *         description: 返回商家信息列表
 *         content:
 *           application/json:
 *             schema:
 *               type: array
 *               items:
 *                 type: object
 *                 properties:
 *                   deleted:
 *                     type: boolean
 *                     example: false
 *                   isPublished:
 *                     type: boolean
 *                     example: false
 *                   _id:
 *                     type: string
 *                     example: "6740199c50ef68f289549524"
 *                   merchantname:
 *                     type: string
 *                     example: "阳光餐厅"
 *                   erweimapic:
 *                     type: string
 *                     format: url
 *                     example: "http://example.com/qrcode.png"
 *                   info:
 *                     type: string
 *                     example: "提供各种美味的中餐"
 *                   pictureurl:
 *                     type: string
 *                     format: url
 *                     example: "http://example.com/image.png"
 *                   sort:
 *                     type: string
 *                     example: "美食"
 *                   town:
 *                     type: string
 *                     example: "阳光小镇"
 *                   createdAt:
 *                     type: string
 *                     format: date-time
 *                     example: "2024-11-22T05:41:48.569Z"
 *                   updatedAt:
 *                     type: string
 *                     format: date-time
 *                     example: "2024-11-22T05:41:48.569Z"
 *                   __v:
 *                     type: integer
 *                     example: 0
 *       500:
 *         description: 服务器错误
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 *                   example: "服务器出现错误"
 */
router.get("/list", verifyToken("admin"), async (ctx) => {
  try {
    const merchants = await MerchantManager.getAllActiveMerchants();
    ctx.status = 200;
    ctx.body = merchants;
  } catch (error) {
    ctx.status = 500;
    ctx.body = { message: error.message };
  }
});

// 修改商家发布状态接口
/**
 * @swagger
 * /merchants/publish-status:
 *   put:
 *     summary: 修改商家发布状态
 *     tags: [Merchant]
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               merchantname:
 *                 type: string
 *                 description: 商家名称
 *                 example: "阳光餐厅"
 *               isPublished:
 *                 type: boolean
 *                 description: 商家是否已发布
 *                 example: true
 *     responses:
 *       200:
 *         description: 发布状态更新成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 *                   example: "发布状态更新成功"
 *                 merchant:
 *                   type: object
 *                   description: 更新后的商家信息
 *                   properties:
 *                     merchantname:
 *                       type: string
 *                       example: "阳光餐厅"
 *                     isPublished:
 *                       type: boolean
 *                       example: true
 *       400:
 *         description: 请求参数不合法
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 *                   example: "Both merchantname and isPublished fields are required."
 *       404:
 *         description: 找不到商家
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 *                   example: "Merchant not found"
 *       500:
 *         description: 服务器错误
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 *                   example: "服务器出现错误"
 */
router.put("/publish-status", verifyToken("admin"), async (ctx) => {
  const { merchantname, isPublished } = ctx.request.body; // 获取请求参数

  if (!merchantname || typeof isPublished !== "boolean") {
    ctx.status = 400;
    ctx.body = {
      message: "Both merchantname and isPublished fields are required.", // TODO: 修改所有消息为中文
    };
    return;
  }

  try {
    const merchant =
      await MerchantManager.getMerchantByMerchantname(merchantname);
    if (!merchant) {
      ctx.status = 404;
      ctx.body = { message: "Merchant not found" };
      return;
    }

    // 更新发布状态
    merchant.isPublished = isPublished;
    await merchant.save();

    ctx.status = 200;
    ctx.body = { message: "发布状态更新成功", merchant };
  } catch (error) {
    ctx.status = 500;
    ctx.body = { message: error.message };
  }
});

/**
 * @swagger
 * /merchants/filter:
 *   get:
 *     summary: 根据小镇名和商店类别获取商店列表
 *     tags: [Merchant]
 *     description: 根据提供的小镇名和商店类别筛选商店，返回符合条件的商店列表。
 *     parameters:
 *       - name: town
 *         in: query
 *         required: true
 *         description: 小镇名
 *         schema:
 *           type: string
 *       - name: sort
 *         in: query
 *         required: true
 *         description: 商店分类（例如 "美食"、"商家"、"客栈"）
 *         schema:
 *           type: string
 *     responses:
 *       200:
 *         description: 返回符合条件的商店列表
 *         content:
 *           application/json:
 *             schema:
 *               type: array
 *               items:
 *                 type: object
 *                 properties:
 *                   merchantname:
 *                     type: string
 *                     description: 商店名称
 *                   erweimapic:
 *                     type: string
 *                     description: 商店二维码图片链接
 *                   info:
 *                     type: string
 *                     description: 商店简介
 *                   pictureurl:
 *                     type: string
 *                     description: 商店介绍图片链接
 *                   sort:
 *                     type: string
 *                     description: 商店分类
 *                   town:
 *                     type: string
 *                     description: 小镇名
 *                   deleted:
 *                     type: boolean
 *                     description: 删除标志
 *                   isPublished:
 *                     type: boolean
 *                     description: 发布状态
 *                   createdAt:
 *                     type: string
 *                     format: date-time
 *                     description: 创建时间
 *                   updatedAt:
 *                     type: string
 *                     format: date-time
 *                     description: 更新时间
 *       400:
 *         description: 请求参数错误，缺失必要的参数或格式不正确
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 error:
 *                   type: string
 *                   description: 错误描述
 *       404:
 *         description: 未找到符合条件的商店
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 *                   description: 提示信息
 *       500:
 *         description: 服务器错误
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 error:
 *                   type: string
 *                   description: 错误描述
 */
router.get("/filter", async (ctx) => {
  const { town, sort } = ctx.query;

  // 验证参数是否完整
  if (!town || !sort) {
    ctx.status = 400;
    ctx.body = { message: "Town 和 Sort 参数是必须的" };
    return;
  }

  try {
    // 获取符合条件的商店
    const merchants = await MerchantManager.getMerchantsByTownAndSort(
      town,
      sort,
    );

    // 如果没有找到符合条件的商店，返回404
    if (!merchants || merchants.length === 0) {
      ctx.status = 404;
      ctx.body = { message: "未找到符合条件的商店" };
      return;
    }

    ctx.status = 200;
    ctx.body = merchants;
  } catch (error) {
    ctx.status = 500;
    ctx.body = { message: error.message };
  }
});

module.exports = { router };
